﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using AcceptServer.Service;
using Common;
using Model;

namespace AcceptServer
{
    public partial class AcceptMainForm : Form
    {
        public AcceptMainForm()
        {
            InitializeComponent();
            label_version.Text = StrVersion;
        }



        public static string ServerWebIp;
        //  private static string _serverLanIp;

        private const string StrVersion = "1.0.2_bata3";
        public  static Hashtable IpEndPointList = Hashtable.Synchronized(new Hashtable());
        private readonly Hashtable _ipEndPointTimeList = Hashtable.Synchronized(new Hashtable());
         
        readonly TQueue<byte[]> _dateQueue = new TQueue<byte[]>();
        public static readonly TQueue<TaxiGpsHistoryInfo> DataQueue = new TQueue<TaxiGpsHistoryInfo>();
        readonly OperateDataBase _operateDataBase = new OperateDataBase();

        private UdpServer _server;
        private UdpServer _server2;

        private static Socket _udpClientChinaNet;
        private static Socket _udpClientUniCom;
        private IPEndPoint _ipepChinaNet;
        private IPEndPoint _ipepUniCom;


        private int _dataHandlerThreadCount = 1;
        private int _dataBaseHandlerThreadCount = 1;


        private Thread[] _threadDataHandler;//数据处理线程
        private Thread[] _threadTaxiGpsHistoryInfoHandler;//数据处理线程

        private Thread _ipEndPointClearThread;
        
        private const string LocalhostIP = "127.0.0.1";
        private ThreadServiceHost _threadServiceHost;
        public static readonly Hashtable TaxiList = Hashtable.Synchronized(new Hashtable());

        public static readonly Hashtable PrivateCarRegistCodeList = Hashtable.Synchronized(new Hashtable());
        private Thread _threadClearTaxi;

        public static string PhoneUserClientVersion="100";
        public static string TaxiClientVersion = "100";
        public static Hashtable OrderList = Hashtable.Synchronized(new Hashtable());
        private Thread _threadClearOrder;

        //!--1
        private void StartServecie()
        {
            if (!CheckDataBasesConnection())
            {
                return;
            }
            
            TaxiClientVersion = OperateConfig.GetTaxiClientVersion();
            PhoneUserClientVersion = OperateConfig.GetPhoneUserClientVersion();

            //----save config
            string[] config = new string[4];
            config[0] = textBox_PosIP.Text;
            config[1] = textBox_ChinaNetIp.Text;
            config[2] = textBox_UnicomIp.Text;
            config[3] = textBox_PhoneNumber.Text;
            OperateConfig.SaveAcceptServerConfig(config);          
            StartWcfService();
            try
            {
 
                if (textBox_ChinaNetIp.Text != LocalhostIP)
                {
                    _server = new UdpServer(textBox_ChinaNetIp.Text, ConstParameters.AstPort);
                    _server.OnReceivedData += server_OnDataReceived;
                    _server.Start();
                }

                if (textBox_UnicomIp.Text != LocalhostIP)
                {
                    _server2 = new UdpServer(textBox_UnicomIp.Text, ConstParameters.AstPort);
                    _server2.OnReceivedData += server_OnDataReceived;
                    _server2.Start();
                }

                if (textBox_ChinaNetIp.Text != LocalhostIP)
                {
                    _ipepChinaNet = new IPEndPoint(IPAddress.Parse(textBox_ChinaNetIp.Text), ConstParameters.AstPort);
                    _udpClientChinaNet = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                    _udpClientChinaNet.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                    _udpClientChinaNet.Bind(_ipepChinaNet);
                }
                if (textBox_UnicomIp.Text != LocalhostIP)
                {
                    _ipepUniCom = new IPEndPoint(IPAddress.Parse(textBox_UnicomIp.Text), ConstParameters.AstPort);
                    _udpClientUniCom = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                    _udpClientUniCom.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                    _udpClientUniCom.Bind(_ipepUniCom);
                }
                _threadTaxiGpsHistoryInfoHandler = new Thread[_dataBaseHandlerThreadCount];
                for (int i = 0; i < _dataBaseHandlerThreadCount; i++)
                {
                    this._threadTaxiGpsHistoryInfoHandler[i] = new Thread(AddTaxiGpsHistoryInfo);
                    this._threadTaxiGpsHistoryInfoHandler[i].Start();
                }

                this._threadDataHandler = new Thread[_dataHandlerThreadCount];
                for (int i = 0; i < _dataHandlerThreadCount; i++)
                {
                    this._threadDataHandler[i] = new Thread(UdpSendData);
                    this._threadDataHandler[i].Start();
                }

                _ipEndPointClearThread = new Thread(IpEndPointClear) { IsBackground = true, Name = "IPEndPointClearThread----------------------------------------------" }; ;
                _ipEndPointClearThread.Start();

                _threadClearTaxi = new Thread(ClearTaxiInCache) { IsBackground = true, Name = "TaxiClearThread ----------------------------------------" }; ;
                _threadClearTaxi.Start();

                _threadClearOrder = new Thread(ClearOrderInThread) { IsBackground = true };
                _threadClearOrder.Start();
            }
            catch (Exception ex)
            {
                InitControlAfterStopService();
                CommonRoutine.HandlingExceptions(ex, true);
                LogService.WriteLog("AcceptMainForm.cs-155");
            }
 
        }

        private void AddTaxiGpsHistoryInfo()
        {
            while (true)
            {
                Thread.Sleep(60 * 60 * 1000);
                if (DataQueue.Count < 1)
                {
                    Thread.Sleep(60000);
                    continue;
                }

                try
                {

                    while (DataQueue.Count > 0)
                    {
                        StringBuilder sb = new StringBuilder();
                        sb.Append("set names  'utf8';insert into ttaxigpshistory");
                        sb.Append("(DriverPhoneNumber,Longitude,Latitude,Updatetime,Taxistate,image) ");
                        sb.Append("values ");
                        int tempCount = 0;
                        while (tempCount < 5000)
                        {
                            if (DataQueue.Count > 0)
                            {
                                tempCount++;
                                TaxiGpsHistoryInfo model = DataQueue.Dequeue();
                                if (model.Taxistate == 21 || model.Taxistate == 22 ||
                                    model.Taxistate == 23 || model.Taxistate == 24)
                                {
                                    model.Taxistate = 2;
                                }
                                if (model.Taxistate == 20)
                                {
                                    model.Taxistate = 0;
                                }
                                sb.Append("('");
                                sb.Append(model.DriverPhoneNumber);
                                sb.Append("','");
                                sb.Append(model.Longitude);
                                sb.Append("','");
                                sb.Append(model.Latitude);
                                sb.Append("','");
                                sb.Append(model.Time);
                                sb.Append("','");
                                sb.Append(model.Taxistate);
                                sb.Append("',");
                                sb.Append("null)");
                                //if (DataQueue.Count > 0)
                                //{
                                //    sb.Append(",");
                                //}   
                                sb.Append(",");
                            }
                            else
                            {
                                break;
                            }

                        }
                        sb.Remove(sb.Length - 1, 1);
                        int rows = _operateDataBase.AddListTaxiGpsHistory(sb.ToString());
                    }


                    //StringBuilder sb = new StringBuilder();
                    //sb.Append("set names  'utf8';insert into ttaxigpshistory");
                    //sb.Append("(DriverPhoneNumber,Longitude,Latitude,Updatetime,Taxistate,image) ");
                    //sb.Append("values ");
                    //while (DataQueue.Count > 0 && tempCount < 10000)
                    //{
                    //    tempCount++;
                    //    TaxiGpsHistoryInfo model = DataQueue.Dequeue();
                    //    sb.Append("('");
                    //    sb.Append(model.DriverPhoneNumber);
                    //    sb.Append("','");
                    //    sb.Append(model.Longitude);
                    //    sb.Append("','");
                    //    sb.Append(model.Latitude);
                    //    sb.Append("','");
                    //    sb.Append(model.Time);
                    //    sb.Append("','");
                    //    sb.Append(model.Taxistate);
                    //    sb.Append("',");
                    //    sb.Append("null)");
                    //    if (DataQueue.Count > 0)
                    //    {
                    //        sb.Append(",");
                    //    }

                    //}
                    //int rows = _operateDataBase.AddListTaxiGpsHistory(sb.ToString());

                    // TaxiGpsHistoryInfo taxiGpsHistoryInfo = DataQueue.Dequeue();
                    //_operateDataBase.AddTaxiGpsHistoryInfo(taxiGpsHistoryInfo);
                }
                catch (Exception ex)
                {
                    LogService.WriteLog(ex.Message);
                    LogService.WriteLog("AcceptMainForm.cs-185");
                }

            }
        }




        void server_OnDataReceived(object sender, EventArgs e)
        {
            SocketAsyncEventArgs socketAsyncEventArgs = e as SocketAsyncEventArgs;
            if (socketAsyncEventArgs != null)
            {
                if (socketAsyncEventArgs.BytesTransferred >= ConstParameters.MhLenth)
                {
                    byte[] receData = new byte[socketAsyncEventArgs.BytesTransferred];
                    Array.Copy(socketAsyncEventArgs.Buffer, 0, receData, 0, receData.Length);
                    byte[] realData = OperateAgreement.RestoreReceData(receData);



                    if (OperateAgreement.JudgeisCompleteData(realData))
                    {
                        string phoneNumber = OperateAgreement.GetPhoneNumInMessageHead(realData);

                        _ipEndPointTimeList[phoneNumber] = DateTime.Now;
                        IpEndPointList[phoneNumber] = socketAsyncEventArgs.RemoteEndPoint;
                        _dateQueue.Enqueue(receData);
                    }

                }

            }


        }

        private void UdpSendData()
        {

            while (true)
            {
                if (_dateQueue.Count < 1)
                {
                    Thread.Sleep(1000);
                    continue;
                }

                byte[] receData;
                lock (_dateQueue)
                {
                    receData = _dateQueue.Dequeue();
                }



                byte[] realData = OperateAgreement.RestoreReceData(receData);
                ushort messageId = OperateAgreement.GetMessageIdInMessageHead(realData);
                string phoneNumber = OperateAgreement.GetPhoneNumInMessageHead(realData);

                Socket sendSocket = JudgeIsUnicomNumber(phoneNumber);



                IPEndPoint ipEndPoint = IpEndPointList[phoneNumber] as IPEndPoint;
                if (ipEndPoint == null) continue;
                byte[] sendData = new byte[1];
                try
                {
                    OperateCmdData operateCmdData = new OperateCmdData(); ;
                    sendData = operateCmdData.AnalysisMessageId(realData, ipEndPoint.Address);
                }
                catch (Exception ex)
                {
                    CommonRoutine.HandlingExceptions(ex);
                    LogService.WriteLog("AcceptMainForm.cs-405");
                    continue;
                }
                #region Send Bytes

                if (sendData != null && sendData.Length >= ConstParameters.MhLenth)
                {
                    try
                    {
                        //  sendSocket.SendTo(sendData, sendData.Length, SocketFlags.None, ipEndPoint);
                        //_server.SendData(sendData, ipEndPoint);
                        _udpClientChinaNet.SendTo(sendData, sendData.Length, SocketFlags.None, ipEndPoint);
                        _udpClientUniCom.SendTo(sendData, sendData.Length, SocketFlags.None, ipEndPoint);
                        
                    }
                    catch (Exception ex)
                    {
                        CommonRoutine.HandlingExceptions(ex);
                        LogService.WriteLog("AcceptMainForm.cs-428");
                        continue;
                    }
                }
                #endregion

            }


            #region LogPrint
            LogService.WriteLog(Thread.CurrentThread.Name + "----Snen Thread 退出----");
            #endregion
        }

        public Socket JudgeIsUnicomNumber(string phoneNumber)
        {
            #region 单线服务器 处理
            //不会出现这种情况。两个都为空的话没程序就没有收发消息的流程。
            // if (_udpClientUniCom == null && _udpClientChinaNet == null) 
            if (_udpClientUniCom == null && _udpClientChinaNet != null)
            {
                _udpClientUniCom = _udpClientChinaNet;
                return _udpClientChinaNet;
            }
            if (_udpClientUniCom != null && _udpClientChinaNet == null)
            {
                _udpClientChinaNet = _udpClientUniCom;
                return _udpClientUniCom;
            }
            #endregion
            //130、131、132、145、155、156、185、186 
            if (phoneNumber.StartsWith("130") || phoneNumber.StartsWith("131") || phoneNumber.StartsWith("132") ||
                phoneNumber.StartsWith("145") || phoneNumber.StartsWith("155") || phoneNumber.StartsWith("156") ||
                phoneNumber.StartsWith("185") || phoneNumber.StartsWith("186"))
            {
                return _udpClientUniCom;
            }
            else
            {
                return _udpClientChinaNet;
            }
        }


        private void IpEndPointClear()
        {
            while (true)
            {
                Thread.Sleep(300 * 1000);
                DateTime now = DateTime.Now;
                ArrayList delKey = new ArrayList();
                lock (_ipEndPointTimeList.SyncRoot)
                {
                    foreach (DictionaryEntry dictionaryEntry in _ipEndPointTimeList)
                    {
                        DateTime updatatime = (DateTime)dictionaryEntry.Value;
                        TimeSpan timeSpan = new TimeSpan(now.Ticks - updatatime.Ticks);
                        if (timeSpan.TotalSeconds > 300)
                        {
                            delKey.Add(dictionaryEntry.Key);
                            LogService.WriteDebugLog(dictionaryEntry.Key + "---" + now.ToString() + "---" + updatatime.ToString() + "退出登录！", DateTime.Now, dictionaryEntry.Key.ToString());
                        }
                    }
                }

                foreach (string phoneNumber in delKey)
                {
                    try
                    {
                        _ipEndPointTimeList.Remove(phoneNumber);
                        IpEndPointList.Remove(phoneNumber);


                    }
                    catch (Exception ex)
                    {
                        CommonRoutine.HandlingExceptions(ex);
                        LogService.WriteLog("AcceptMainForm.cs-515");
                    }

                }
                Invoke(new MethodInvoker(delegate()
                {
                    label_SokcetCount.Text = IpEndPointList.Count.ToString(CultureInfo.InvariantCulture) + "," + DateTime.Now.ToString();
                }));


            }

        }



        private void InitControlAfterStopService()
        {
            spState.Text = @" 监听服务未启动 ...";
            button_startListening.Enabled = true;
            button_stopListening.Enabled = false;
            textBox_PosIP.Enabled = true;
            textBox_ChinaNetIp.Enabled = true;
            textBox_UnicomIp.Enabled = true;
            textBox_PhoneNumber.Enabled = true;
            textBox_DataBaseHandlerThreadCount.Enabled = true;
            textBox_DataHandlerThreadCount.Enabled = true;

            textBox_datBaseName.Enabled = true;
            textBox_passWord.Enabled = true;
            textBox_serverName.Enabled = true;
            textBox_userName.Enabled = true;

            if (_threadDataHandler != null)
            {
                //终止所有的数据处理线程
                for (int i = 0; i < _dataHandlerThreadCount; i++)
                {
                    if (this._threadDataHandler[i].IsAlive) this._threadDataHandler[i].Abort();
                }
            }

            if (_threadTaxiGpsHistoryInfoHandler != null)
            {
                //终止所有的数据处理线程
                for (int i = 0; i < _dataBaseHandlerThreadCount; i++)
                {
                    if (this._threadTaxiGpsHistoryInfoHandler[i].IsAlive) this._threadTaxiGpsHistoryInfoHandler[i].Abort();
                }
            }
             
            //if (_addTaxiGpsHistoryInfoQueue != null) _addTaxiGpsHistoryInfoQueue.Abort();
            if (_ipEndPointClearThread != null) _ipEndPointClearThread.Abort();
      
            // if (_server != null) { _server.Stop(); }
             
        }



        private void InitControlAfterStartService()
        {
            spState.Text = @" 监听服务已启动 ...";
            button_startListening.Enabled = false;
            button_stopListening.Enabled = true;
            textBox_PosIP.Enabled = false;
            textBox_ChinaNetIp.Enabled = false;
            textBox_UnicomIp.Enabled = false;
            textBox_PhoneNumber.Enabled = false;
            textBox_DataBaseHandlerThreadCount.Enabled = false;
            textBox_DataHandlerThreadCount.Enabled = false;

            textBox_datBaseName.Enabled = false;
            textBox_passWord.Enabled = false;
            textBox_serverName.Enabled = false;
            textBox_userName.Enabled = false;
        }

  
        private void button_startListening_Click(object sender, EventArgs e)
        {
            if (!CommonRoutine.IsValidIp(textBox_PosIP.Text))
            {
                MessageBox.Show(@"请检查位置服务器IP格式");
                textBox_PosIP.Focus();
                return;
            }
            if (!CommonRoutine.IsValidIp(textBox_ChinaNetIp.Text))
            {
                MessageBox.Show(@"请检查接入服务器IP1格式");
                textBox_ChinaNetIp.Focus();
                return;
            }
            if (!CommonRoutine.IsValidIp(textBox_UnicomIp.Text))
            {
                MessageBox.Show(@"请检查接入服务器IP2格式");
                textBox_UnicomIp.Focus();
                return;
            }


            if (!int.TryParse(textBox_DataBaseHandlerThreadCount.Text, out _dataBaseHandlerThreadCount))
            {
                MessageBox.Show(@"数据库处理线程数：  请输入数字");
                textBox_DataBaseHandlerThreadCount.Focus();
                return;
            }
            if (!int.TryParse(textBox_DataHandlerThreadCount.Text, out _dataHandlerThreadCount))
            {
                MessageBox.Show(@"网络数据处理线程数 ：请输入数字");
                textBox_DataHandlerThreadCount.Focus();
                return;
            }
            StartServecie();

        }

        private void button_stopListening_Click(object sender, EventArgs e)
        {

            try
            {
                IpEndPointList.Clear();
                _ipEndPointTimeList.Clear();
                label_SokcetCount.Text = "0";
                InitControlAfterStopService();

            }
            catch (Exception ex)
            {
                CommonRoutine.HandlingExceptions(ex);
                LogService.WriteLog("AcceptMainForm.cs-891");
            }

        }

        private void HideServer_Click(object sender, EventArgs e)
        {
            WindowState = FormWindowState.Minimized;
            ShowInTaskbar = false;
            Visible = false;
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            button_startListening.Enabled = true;
            button_stopListening.Enabled = false;
            string[] config = OperateConfig.GetAcceptServerConfig();
            if (config != null && config.Length == 8)
            {
                textBox_PosIP.Text = config[0];
                textBox_ChinaNetIp.Text = config[1];
                textBox_UnicomIp.Text = config[2];
                textBox_PhoneNumber.Text = config[3];            
                textBox_datBaseName.Text = config[4];
                textBox_serverName.Text = config[5];
                textBox_userName.Text = config[6];
                textBox_passWord.Text = config[7];
            }
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                IpEndPointList.Clear();
                label_SokcetCount.Text = "0";

                InitControlAfterStopService();

            }
            catch (Exception ex)
            {
                CommonRoutine.HandlingExceptions(ex);
                LogService.WriteLog("AcceptMainForm.cs-943");
            }
            notifyIcon1.Visible = false;
            Environment.Exit(0);
        }

        private void notifyIcon1_Click(object sender, EventArgs e)
        {
            if (WindowState == FormWindowState.Minimized)
            {
                WindowState = FormWindowState.Normal;
                ShowInTaskbar = true;
                Visible = true;
                Focus();
            }
            else
            {
                WindowState = FormWindowState.Minimized;
                ShowInTaskbar = false;
                Visible = false;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            string showtext = IpEndPointList.Count.ToString();

            OrderInfo order = new OrderInfo();
            order.PassengerName = "董小姐";
            order.PhoneNumber = "13666666666";
            order.StartLat = 30.475289;
            order.StartLng = 114.40746;
            order.EndLat = 30.462011;
            order.EndLng = 114.416545;
            order.State = OrderState.S1_NewOrder;
            order.CallTime = DateTime.Now;
            order.AgreeStartTime = DateTime.Now.AddHours(32);
            order.PhoneOrderId = DateTime.Now.ToString("ddHHmmss");
            OperateDataBase operateDataBase = new OperateDataBase();
            int id = operateDataBase.OrderAdd(order);
            if (id > 0)
            {                              
                order.Id = id;
                OrderList.Add(id, order);
            }



            //lock (_ipEndPointList.SyncRoot)
            //{
            //    foreach (DictionaryEntry dictionaryEntry in _ipEndPointList)
            //    {
            //        showtext = showtext + dictionaryEntry.Key + Environment.NewLine;
            //    }
            //}
            MessageBox.Show(showtext);
        }

        private void button_TestConnection_Click(object sender, EventArgs e)
        {
            string[] config = new[]
            {
                 textBox_datBaseName.Text,
                 textBox_serverName.Text,
                 textBox_userName.Text,
                textBox_passWord.Text
            };
            OperateConfig.SaveAcceptServerDataBaseConfig(config);
            if (CheckDataBasesConnection())
            {
                BLL.SysManage.UpdataConnectstring();
                MessageBox.Show(@"数据库连接成功！");

            }
        }

        /// <summary>
        ///!--4 return 1 means succeed ,return 0 means false
        /// </summary>
        public bool CheckDataBasesConnection()
        {
            if (BLL.SysManage.CheckDb(textBox_datBaseName.Text) == 0)
            {
                MessageBox.Show(@"系统数据库连接失败！请检查配置。");
                return false;
            }
            return true;
        }



        private void button1_Click(object sender, EventArgs e)
        {

            label_SokcetCount.Text = IpEndPointList.Count.ToString();
            label_DataHandlerThreadCount.Text = _dateQueue.Count.ToString();
            label_DataBaseHandlerThreadCount.Text = DataQueue.Count.ToString();
            TaxiClientVersion = OperateConfig.GetTaxiClientVersion();
            PhoneUserClientVersion = OperateConfig.GetPhoneUserClientVersion();
        }

        private void ClearTaxiInCache()
        {
            while (true)
            {            
                Thread.Sleep(180 * 1000);
                DateTime now = DateTime.Now;
                ArrayList delKey = new ArrayList();
                lock (TaxiList.SyncRoot)
                {

                    foreach (TaxiInfo taxiInfo in TaxiList.Values)
                    {
                       DateTime updatatime = taxiInfo.UpdateTime;
                       TimeSpan timeSpan = new TimeSpan(now.Ticks - updatatime.Ticks);
                       if (timeSpan.TotalSeconds > 300)
                       {
                            delKey.Add(taxiInfo.PhoneNumber);
                            LogService.WriteDebugLog(taxiInfo.PhoneNumber+ "---" 
                                + now.ToString() + "---" + updatatime.ToString() + "退出登录！", DateTime.Now);
                       }
                    }
                  
                }

                foreach (string phoneNumber in delKey)
                {
                    try
                    {
                        TaxiList.Remove(phoneNumber);
                        //_ipEndPointTimeList.Remove(phoneNumber);
                        //_ipEndPointList.Remove(phoneNumber);
                    }
                    catch (Exception ex)
                    {
                        CommonRoutine.HandlingExceptions(ex);
                        LogService.WriteLog("AcceptMainForm.cs-515");
                    }

                }
                //Invoke(new MethodInvoker(delegate()
                //{
                //    label_SokcetCount.Text = _ipEndPointList.Count.ToString(CultureInfo.InvariantCulture) + "," + DateTime.Now.ToString();
                //}));
            }
        }

        private void ClearOrderInThread()
        {
            DateTime tomarrow = DateTime.Now.AddDays(1).Date;
            TimeSpan timeSpan = tomarrow - DateTime.Now;
            Thread.Sleep(timeSpan.Seconds * 1000);
            while (true)
            {
                //---------------清理订单--------------
                lock (OrderList.SyncRoot)
                {
                    foreach (OrderInfo order in OrderList.Values)
                    {
                        
                        switch (order.State)
                        {
                                case OrderState.S0_Cancled:

                                break;
                                case OrderState.S1_NewOrder:
                                break;
                                case OrderState.S2_TakenByPlatform:
                                break;
                                case OrderState.S3_SetCarAndDriver:
                                break;
                                case OrderState.S4_OrderPaid:
                                break;
                                case OrderState.S5_SentInfo:
                                break;
                                case OrderState.S6_AcceptByDriver:
                                break;
                                case OrderState.S7_Finish:
                                break;
                                case OrderState.S9_Unknown:
                                break;
                        }
                    }
                }
                DateTime nextDay = DateTime.Now.AddDays(1).Date;
                TimeSpan ts = nextDay - DateTime.Now;
                Thread.Sleep(ts.Seconds*1000);
            }
        }


        private void StartWcfService()
        {            
            try
            {
                _threadServiceHost = new ThreadServiceHost();
                _threadServiceHost.Start();
                InitControlAfterStartService();      
            }
            catch (Exception ex)
            {
                CommonRoutine.HandlingExceptions(ex, true);
                //OperateConfig.SavePosServerConfig("0", comstr);
                System.Diagnostics.Process.Start(System.Reflection.Assembly.GetExecutingAssembly().Location);
                Environment.Exit(0);
            }
        }

        public static void SendDataToIpAddress(byte[] data, IPEndPoint ipEndPoint, string sendToPhoneNumber)
        {
        
          if (_udpClientChinaNet != null)
             _udpClientChinaNet.SendTo(data, data.Length, SocketFlags.None, ipEndPoint);
          if (_udpClientUniCom != null)
             _udpClientUniCom.SendTo(data, data.Length, SocketFlags.None, ipEndPoint);
        }

    }

}
